var express = require("express");
var router = express.Router();
const puppeteer = require("puppeteer");
const { exec } = require("child_process");
const fs = require("fs");
const {
  handleSharpBuffer,
  handleLinkBuffer,
  ICOLinkBuffer,
} = require("../utils/sharp.js");
const { getWebLogo } = require("../apis/images.js");
const dayjs = require("dayjs");

let browserMap = {
  0: { browser: null, page: null },
};

let pathUrl = "D:\\图库\\导航截图\\";
let imageBaseUrl = "http://127.0.0.1:3000/nav-images/";

const writeBinaryFile = (path, data) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, "binary", (err) => {
      if (err) {
        console.log(err, "-----");
      } else {
        console.log(path, "下载成功", `finish`);
      }
      resolve();
    });
  });
};

const createMkdir = (dirName) => {
  return new Promise((resolve, reject) => {
    let dir = pathUrl + dirName;
    // 下载截图
    fs.mkdir(dir, { recursive: true }, async (err) => {
      console.log(err, "mkdir");
      // 创建文件夹成功
      if (!err) {
        resolve();
      } else {
        console.log("make dir fail");
        reject();
      }
    });
  });
};

const runBrowser = async (urls, dirName, carry_out_id) => {
  // 启动浏览器

  if (!browserMap[carry_out_id].browser) {
    console.log(browserMap[carry_out_id].browser, "browser1");

    browserMap[carry_out_id].browser = await puppeteer.launch({
      // devtools: true,
      // slowMo: 1000,
      headless: false,
      args: ["--start-maximized"],
      defaultViewport: null,
    });
  }

  // 创建一个新页面
  browserMap[carry_out_id].page = await browserMap[
    carry_out_id
  ].browser.newPage();

  console.log(urls, urls[0], "urls");

  try {
    // 访问一个网址
    await browserMap[carry_out_id].page
      .goto(urls[0], { timeout: 30 * 1000, waitUntil: "networkidle0" })
      .catch((err) => {
        console.log(err);
      });
    // await page.waitForNavigation({ waitUntil: "networkidle0" });
    console.log(browserMap[carry_out_id], "browserMap[carry_out_id]----");
    if (browserMap[carry_out_id].page.waitForTimeout) {
      await browserMap[carry_out_id].page.waitForTimeout(1000);
    }
  } catch (error) {
    console.log(error);
  }

  // await page.waitForNavigation();

  let webInfo = {
    title: "",
    description: "",
    keywords: "",
    icons: [],
    dir: pathUrl + dirName,
  };

  if (await browserMap[carry_out_id].page.$("title")) {
    webInfo.title = await browserMap[carry_out_id].page.title();
    console.log(webInfo.title, "webInfo.title");
  }

  if (await browserMap[carry_out_id].page.$('meta[name="description"]')) {
    webInfo.description = await browserMap[carry_out_id].page.$eval(
      'meta[name="description"]',
      (element) => element.getAttribute("content")
    );
    console.log(webInfo.description, "webInfo.description");
  }

  if (await browserMap[carry_out_id].page.$('meta[name="keywords"]')) {
    webInfo.keywords = await browserMap[carry_out_id].page.$eval(
      'meta[name="keywords"]',
      (element) => element.getAttribute("content")
    );
    console.log(webInfo.keywords, "webInfo.keywords");
  }

  let screenBuffer = [];
  const buffer = await browserMap[carry_out_id].page.screenshot();
  screenBuffer.push(buffer);

  for (let index = 1; index < urls.length; index++) {
    const element = urls[index];
    await browserMap[carry_out_id].page.goto(element);
    const buffer = await browserMap[carry_out_id].page.screenshot();
    screenBuffer.push(buffer);
  }

  console.log(screenBuffer, "screenBuffer信息");
  await createMkdir(dirName).catch((err) => {
    console.error(err);
  });

  console.log(webInfo, "下载信息");

  return webInfo;
};

router.get("/automateCrawlingNav", async (req, res) => {
  const { urls, name, carry_out_id } = req.query;
  if (!browserMap[carry_out_id]) {
    browserMap[carry_out_id] = {};
  }

  const browserRes = await runBrowser(
    urls.split("\n"),
    name,
    carry_out_id
  ).catch((err) => {
    console.log(err, "err");
  });

  res.send({
    name: name,
    urls: urls.split("\n"),
    browserRes: browserRes,
  });
});

router.get("/automateScreenNav", async (req, res) => {
  const { urls, name, carry_out_id } = req.query;
  let dir = pathUrl + name;

  const buffer = await browserMap[carry_out_id].page.screenshot();
  let compressedBuffer = await handleSharpBuffer(buffer).catch((err) => err);
  const imageName = `/screen_${dayjs(Date.now()).format("YYYYMMDDHHmmss")}.png`;
  await writeBinaryFile(dir + imageName, compressedBuffer);

  res.send({
    name: name,
    image_url: imageBaseUrl + name + imageName,
  });
});

router.get("/automateLogoNav", async (req, res) => {
  const { urls, name, carry_out_id } = req.query;
  let dir = pathUrl + name;

  let icons = [];

  try {
    if (await browserMap[carry_out_id].page.$('link[rel~="icon"]')) {
      icons = await browserMap[carry_out_id].page.evaluate(() => {
        const links = document.querySelectorAll('link[rel~="icon"]');
        const icons = Array.from(links).map((link) => link.href);
        return icons;
      });

      if (!icons.length) {
        console.log("----------不存在link-icon--------");
        icons = await browserMap[carry_out_id].page.$$eval("img", (images) =>
          images.map((img) => img.src)
        );
      }

      if (!icons.length) {
        console.log("----------不存在img-icon--------");
        icons = await browserMap[carry_out_id].page.evaluate(() => {
          const links = document.querySelectorAll("link");
          const icons = Array.from(links)
            .map((link) => link.href)
            .filter((v) => v.indexOf(".png") != -1 || v.indexOf(".jpg") != -1);
          return icons;
        });
      }

      console.log(icons, "icons");
    }

    let logoImages = [];
    for (let index = 0; index < icons.length; index++) {
      const element = icons[index];
      const imageName = `/logo_${index}.png`;

      const isIco = element.indexOf(".ico") !== -1;

      if (isIco) {
        logoImages.push(element);
      } else {
        let res = await getWebLogo(element).catch((err) => {
          return err;
        });

        let _compressedBuffer = res.data;
        const isSvg = element.indexOf(".svg") !== -1;
        console.log(isSvg, isIco, "isSvg || isIco");

        if (isSvg) {
          _compressedBuffer = await handleSharpBuffer(res.data).catch(
            (err) => err
          );

          console.log(_compressedBuffer, "_compressedBuffer");
        }
        //  if (isSvg) {
        //   ICOLinkBuffer
        // }

        await writeBinaryFile(dir + imageName, _compressedBuffer);
        logoImages.push(imageBaseUrl + name + imageName);
      }
    }

    res.send({
      name: name,
      image_urls: logoImages,
    });
  } catch (error) {
    console.log(error, "error");
    res.send({ error });
  }
});

router.get("/automateOverNav", async (req, res) => {
  const { urls, name, carry_out_id } = req.query;
  if (browserMap[carry_out_id] && browserMap[carry_out_id].browser) {
    await browserMap[carry_out_id].browser.close();
    browserMap[carry_out_id].browser = null;
  }

  res.send({
    msg: "已关闭",
  });
});

router.get("/automateOpenFile", async (req, res) => {
  const { urls, name, carry_out_id } = req.query;
  // 执行cmd命令，打开资源管理器到该文件夹目录下，观察图片下载
  exec(`Explorer /root,${pathUrl + name}`, (err, data, stderr) => {
    if (err) {
      console.log("exec");
      res.send({
        msg: "已打开",
      });
    } else {
      res.send({
        msg: "错误",
      });
    }
  });
});

module.exports = router;
